package com.zhu.file;

import com.zhu.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@Slf4j
public class FileController {

    @Value("${file.location}")
    public String baseUrl;

    @PostMapping("/upload")
    public Result<String> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error("文件为空，请选择一个有效的文件。");
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        final String format = simpleDateFormat.format(new Date());
        try {
            // 创建上传目录
            File directory = new File(baseUrl + format);
            if (!directory.exists()) {
                directory.mkdirs();
            }

            // 获取文件名并保存文件
            String fileName = file.getOriginalFilename();
            File destinationFile = new File(directory, fileName);
            file.transferTo(destinationFile);
            return Result.success(format + "/" + fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("文件上传失败");
        }
    }


    @GetMapping("/download")
    public void downloadFile(@RequestParam(value = "fileName") String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
        File file = new File(baseUrl + fileName);
        if (!file.exists()) {
            log.warn("文件不存在{}", file.getPath());
            return;
        }
        response.setContentType("application/octet-stream"); // 文件类型
        String encodedFileName = URLEncoder.encode(file.getName(), "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");
        response.setContentLength((int) file.length());
        try (FileInputStream inputStream = new FileInputStream(file);
             OutputStream outputStream = response.getOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            e.printStackTrace();
        }
    }
}

